home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 17569 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: grimsel.zurich.ibm.com!usenet
  2. From: Keith Whittingham <wgk@zurich.ibm.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: casting w/ virtual base classes
  5. Date: Tue, 16 Apr 1996 17:01:49 -0700
  6. Organization: IBM Zurich Research Laboratory
  7. Message-ID: <317434ED.1C4F@zurich.ibm.com>
  8. References: <31728499.6201DD56@unisql.com> <317396ED.ABD322C@intellektik.informatik.th-darmstadt.de>
  9. NNTP-Posting-Host: pine.zurich.ibm.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.01 (Win16; I)
  14.  
  15. Enno Sandner wrote:
  16. > > class Derived : public virtual Base {...};
  17. > >
  18. > >         Base* foo(void) {...}
  19. > >
  20. > >         Derived *dp1 = foo();
  21. > >         Derived *dp2 = (Derived *) foo();
  22. > >
  23. > > error: cast: Base* ->derived dp2*; Base is virtual base
  24. > > Q1: Is the double cast legal? Why? / Why not?
  25. > It's legal -- but the result is undefined.
  26. > The forthcoming C++ standard provides a special cast-operator
  27. > for this purpose. The 'dynamic_cast'
  28. >         Derived* dp=dyanmic_cast<Derived*>(foo());
  29. > will safely narrow the pointer (*). If the returned object
  30. > is not an object of a subclass of 'Dervived', the dynamic_cast
  31. > expression returns a null-pointer.
  32.  
  33. The purpose of the dynamic_cast is to downcast after checking
  34. that object is of the target type or, presumably, in the hierarchy:
  35.  
  36.  class A {} *a;
  37.  class B: public A {} *pb;
  38.  class C: public B {} c, *pc;
  39.  
  40.  a = &c;
  41.  pb = dynamic_cast<B *> a;  // not sure about this
  42.  pc = dynamic_cast<C *> a; 
  43.  
  44. I have implemented this using basic C++ (i.e. convertion
  45. operators) so that this works with or without cast
  46. operators and without the need for any cast, dynamic
  47. or otherwise.
  48.  
  49.  pb = (B *)a;
  50.  pb = a;  // Works also!
  51.  
  52. But I digress. The original posters question is based on the 
  53. fact that the base class is virtual so that a cast error
  54. occurs which is the case and is correct. I guess it is to
  55. do with the implementation of virtual base classes not 
  56. being a contiguous memory block but am not sure...
  57.  
  58.  
  59. -- 
  60. Keith Whittingham
  61. wgk@zurich.ibm.com
  62.